package com.xiejr.util;

import cn.hutool.core.util.IdUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xiejr.context.ApplicationContextHolder;
import com.xiejr.model.exception.BusinessException;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: odf-editor-system
 * @description: JWT鉴权工具
 * @author: xjr
 * @create: 2020-07-21 11:28
 **/

public final class JwtUtil {

    /**
     * token私钥
     */
    public static final String TOKEN_SECRET = "7d995aa0a3f6c493977d36c57da0a8dea3c691323b2eaf2212f8cee1960144ac";

    public static final String SALT="salt";

    public static final String USER_ID="userId";

    /**
     * @param userId
     * @return
     */
    public static String sign(String userId){
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
        return JWT.create().withHeader(header)
                .withClaim("userId",userId).withClaim(SALT, IdUtil.simpleUUID()).sign(algorithm);
    }


    private static DecodedJWT verity(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt;
        } catch (IllegalArgumentException e) {
            return null;
        } catch (JWTVerificationException e) {
            return null;
        }

    }



    public static Map<String, Claim> decode(String token)throws BusinessException {
        if (verity(token)==null){
            throw new BusinessException("令牌无效");
        }
        return JWT.decode(token).getClaims();
    }

    public static void main(String[] args) {
        System.out.println(JwtUtil.sign("xiaoxie"));
    }

    public static void setGlobalEmptyToken(){
        ApplicationContextHolder.set(ApplicationContextHolder.T,"");
        ApplicationContextHolder.set(ApplicationContextHolder.TS,"");
    }
}
